<?php

namespace App\Lib\Pay\Applepay;
class ApplePayResults
{
    public static $url = 'https://buy.itunes.apple.com/verifyReceipt';
    public static $sandbox_url = 'https://sandbox.itunes.apple.com/verifyReceipt';
    
    /**
     * 验证AppStore内付
     */
    public static function validate_apple_pay($receipt_data, $app_product_id)
    {
        // 验证参数
        if (strlen($receipt_data) < 20) {
            return false;
        }
        // 请求验证
        $html = self::acurl($receipt_data);
        $data = json_decode($html, true);
        // 如果是沙盒数据 则验证沙盒模式
        if ($data['status'] == '21007') {
            // 请求验证
            $html = self::acurl($receipt_data, 1);
            $data = json_decode($html, true);
            $data['sandbox'] = '1';
        }

        // 判断是否购买成功
        if (intval($data['status']) === 0) {
            if ($data['receipt']['in_app'][0]['product_id'] != $app_product_id){
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    public static function get_order_info($receipt_data){
        // 验证参数
        if (strlen($receipt_data) < 20) {
            return null;
        }
        // 请求验证
        $html = self::acurl($receipt_data);
        $data = json_decode($html, true);
        // 如果是沙盒数据 则验证沙盒模式
        if ($data['status'] == '21007') {
            // 请求验证
            $html = self::acurl($receipt_data, 1);
            $data = json_decode($html, true);
            $data['sandbox'] = '1';
        }
        // 判断是否购买成功
        if (intval($data['status']) !== 0) {
            return null;
        }
        if (!isset($data['receipt'])){
            return null;
        }
        if (!isset($data['receipt']['in_app'])){
            return null;
        }
        $in_app = $data['receipt']['in_app'];
        $ret_data = [];
        foreach ($in_app as $item){
            $item_data = [
                'product_id' => $item['product_id'],
                'bundle_id' => $data['receipt']['bundle_id'],
                'transaction_id' => $item['transaction_id'],
                'purchase_date_ms' => $item['purchase_date_ms'],
            ];
            $ret_data [] = $item_data;
        }
        return $ret_data;
    }

    
    public static function acurl($receipt_data, $sandbox = false)
    {
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS);
        
        $url = $sandbox ? self::$sandbox_url : self::$url;
        
        //简单的curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    
}